const { ccclass } = cc._decorator;


// export type Constructor<T = unknown> = new (...args: any[]) => T;
// export type AssetType<T = cc.Asset> = Constructor<T>;
export type LoadCompleteCallback<T> = (error: Error | null, asset: T) => void;

@ccclass('ResUtil')
export class ResUtil {

    /** 已加载过的Prefab */
    private static localLoaded: Map<string, cc.Asset> = new Map();


    /**
     * 加载 `prefab/` 下Prefab
     * @param name 名称
     * @param cb 加载完成回调
     */
    public static getPrefab(name: string, cb: LoadCompleteCallback<cc.Prefab>) {
        let result: cc.Asset = this.localLoaded.get(name);
        if (result) {
            // cc.log(`已经加载 ${name}`);
            if (cb) { cb(null, result as cc.Prefab); }
        }
        else {
            // cc.log(`还没加载 ${name}`);
            this.loadRes(`prefabs/${name}`, cc.Prefab, cb);
        }
    }

    public static loadRes<T extends cc.Asset>(url: string, type: typeof cc.Asset, cb?: LoadCompleteCallback<T>) {
        if (type) {
            cc.resources.load(url, type, (err, res) => {
                if (err) {
                    cc.error(err.message || err);
                    if (cb) { cb(err, res as T); }
                    return;
                }

                this.localLoaded.set(url.split('/')[2], res);

                if (cb) { cb(err, res as T); }
            });
        } else {
            cc.resources.load(url, (err, res) => {
                if (err) {
                    cc.error(err.message || err);
                    if (cb) { cb(err, res as T); }

                    return;
                }

                if (cb) { cb(err, res as T); }
            });
        }
    }
}